package 二叉树相关问题.BST;

import java.util.ArrayList;
import java.util.List;

public class 二叉搜索树中的众数 {
    List<Integer> list = new ArrayList<>();
    int preVal=0,curTimes=0,maxTimes=0;
    public int[] findMode(TreeNode root) {
       traverse(root);
       int n=list.size();
        int[] res = new int[n];
        for (int i = 0; i < n; i++) {
            res[i]=list.get(i);
        }
        return res;
    }

    private void traverse(TreeNode root) {
        if (root==null)
            return;
        traverse(root.left);
        if (root.val==preVal)
            curTimes++;
        else{
            preVal=root.val;
            curTimes=1;
        }
        if (curTimes==maxTimes){
            list.add(root.val);
        }
        else if(curTimes>maxTimes){
            list.clear();
            maxTimes=curTimes;
            list.add(root.val);
        }
        traverse(root.right);
    }
}
